# apps/audit/utils.py
from .models import AuditLog
from django.contrib.auth import get_user_model

User = get_user_model()

def log_action(user, action, model_name, object_id, object_repr, changes=None, request=None):
    """
    记录审计日志
    """
    username = user.username if user else 'system'
    ip = getattr(request, 'client_ip', '')
    ua = getattr(request, 'user_agent', '')

    AuditLog.objects.create(
        user=user,
        username=username,
        action=action,
        model_name=model_name,
        object_id=object_id,
        object_repr=object_repr,
        changes=changes,
        ip_address=ip,
        user_agent=ua
    )